package com.bci.pwtz.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;


public class FtpUtil extends FTPClient
{
    private static final Logger _logger = Logger.getLogger(FtpUtil.class);


    private FtpUseBean ftpUseBean;

    // 获取目标路径下的文件属性信息，主要是获取文件的size
    // private FTPFile[] files;

    public FtpUseBean getFtpUseBean()
    {
        return ftpUseBean;
    }

    public FtpUtil()
    {
        super();
    }

    public void setFtpUseBean(FtpUseBean ftpUseBean)
    {
        this.ftpUseBean = ftpUseBean;
    }

    public boolean ftpLogin()
    {
        boolean isLogined = false;
        try
        {
            _logger.debug("ftp login start ...");
            int repeatTime = ftpUseBean.getRepeatTime();
            for (int i = 0; i < repeatTime; i++)
            {
                super.connect(ftpUseBean.getHost(), ftpUseBean.getPort());
                isLogined = super.login(ftpUseBean.getUserName(), ftpUseBean.getPassword());
                if (isLogined)
                    break;
                super.enterLocalPassiveMode();
            }
            if (isLogined)
                _logger.debug("ftp login successfully ...");
            else
                _logger.debug("ftp login failed ...");
            return isLogined;
        }
        catch (SocketException e)
        {
            _logger.error("", e);
            return false;
        }
        catch (IOException e)
        {
            _logger.error("", e);
            return false;
        }
        catch (RuntimeException e)
        {
            _logger.error("", e);
            return false;
        }
    }

    public void setFtpToUtf8() throws IOException
    {

        FTPClientConfig conf = new FTPClientConfig();
        super.configure(conf);
        // super.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = super.sendCommand("OPTS UTF8 ON");
        if (reply == 200)
        { // UTF8 Command
            super.setControlEncoding("UTF-8");
        }

    }

    public void close()
    {
        if (super.isConnected())
        {
            try
            {
                super.logout();
                super.disconnect();
                _logger.debug("ftp logout ....");
            }
            catch (Exception e)
            {
                _logger.error(e.getMessage());
                throw new RuntimeException(e.toString());
            }
        }
    }

    public void uploadFileToFtpByIS(InputStream inputStream, String fileName) throws IOException
    {
        super.storeFile(ftpUseBean.getFtpPath() + fileName, inputStream);
    }

    public boolean downFtpFile(String fileName, String localFileName) throws IOException
    {
        boolean result=false;
        File outfile = new File(localFileName);
        OutputStream oStream = null;
        try
        {
            oStream = new FileOutputStream(outfile);
            result=super.retrieveFile(new String((ftpUseBean.getFtpPath() + fileName).getBytes("UTF-8"),"ISO-8859-1"), oStream);
        }
        finally
        {
            if (oStream != null)
                oStream.close();
        }
        return result;
    }

    public FTPFile[] listFtpFiles() throws IOException
    {
        return super.listFiles(ftpUseBean.getFtpPath());
    }

    public void deleteFtpFiles(FTPFile[] ftpFiles) throws IOException
    {
        String path = ftpUseBean.getFtpPath();
        for (FTPFile ff : ftpFiles)
        {
            if (ff.isFile())
            {
                if (!super.deleteFile(path + ff.getName()))
                    throw new RuntimeException("delete File" + ff.getName() + " is n't seccess");
            }
        }
    }

    public void deleteFtpFile(String fileName) throws IOException
    {
        if (!super.deleteFile(ftpUseBean.getFtpPath() + fileName))
            throw new RuntimeException("delete File" + ftpUseBean.getFtpPath() + fileName + " is n't seccess");
    }

    public InputStream downFtpFile(String fileName) throws IOException
    {
        return super.retrieveFileStream(ftpUseBean.getFtpPath() + fileName);
    }
}
